$(function () {
    //展开对应的子模块
    var path = window.location.pathname;
    var index = path.lastIndexOf('/');
    path = path.slice(0, index);
    $('.layui-nav-tree .layui-child .parentCate').each(function () {
        if ($(this).attr('data-url') == path) {
            $(this).next().show();
        }
    })

    $('.layui-nav-tree .layui-child .parentCate span').on('click', function () {
        $(this).parent().next().show();
        $(this).parents('li').siblings().find('.layui-nav-child').hide();
    })
})

function checkForm() {
    pass = true;
    end = '';
    start = '';
    endText = '';
    startText = '';
    $("td:contains('*')").next().find('input').each(function () {
        if (this.value == '') {
            text = $(this).attr('title');
            layer.msg(text + "是必填项", {'icon': 2});
            this.focus();
            pass = false;
            return false;//跳出each
        }
        var title = $(this).attr('title');
        if (title.indexOf('天数') >= 0) {
            var regu = "^[0-9]+\.?[0-9]*$";
            var re = new RegExp(regu);
            if (!re.test($(this).val())) {
                layer.msg(title + "必须为数字", {'icon': 2});
                this.focus();
                pass = false;
                return false;//跳出each
            }
        }

        if (title.indexOf('结束时间') >= 0 || title.indexOf('结束日期') >= 0) {
            endText = title;
            end = $(this).val();
        }
        if (title.indexOf('开始时间') >= 0 || title.indexOf('开始日期') >= 0) {
            startText = title;
            start = $(this).val();
        }
    });
    if (end < start) {
        layer.msg(endText + '不能小于' + startText, {'icon': 2});
        this.focus();
        pass = false;
        return false;//跳出each
    }

    if (!pass) {
        return false;
    }
    
    $("td:contains('*')").next().find('textarea').each(function () {
        if ($(this).val() == '') {
            text = $(this).attr('title');
            layer.msg(text + "是必填项", {'icon': 2});
            this.focus();
            pass = false;
            return false;//跳出each
        }
    });
    
    $("td:contains('*')").next().find('select').each(function () {
        if (this.value == '') {
            text = $(this).parent().prev().text();
            layer.msg(text + "是必填项");
            this.focus();
            pass = false;
            return false;//跳出each
        }
    });
    return pass;
}

$("body").on('click', '.btn-submit', function () {
    //验证表单
    if (!checkForm()) {
        return;
    }

    var _this = $(this);
    var str = _this.data('verify');
    var url = _this.attr('data-url');
    var form = _this.attr('data-form');
    if (!form) {
        var data = $('body').find('form').serialize();
    } else {
        var data = $('body').find('#form-' + form).serialize();
    }
    var len = data.length;
    var submit = true;
    if (submit) {
        if (_this.hasClass('ajax-post')) {
            var index = layer.load(2, {shade: false});
            $.ajax({
                url: url,
                data: data,
                type: 'post',
                success: function (data) {
                    console.log(data);

                    //如果是流程转交后发起修改待办事项的ajax
//                    if(data.remind == 1){
//                        var remindUrl = $('#indexRemindUrl').val();
//                        $.get(remindUrl,function(res){
//                            console.log(res)
//                            if(res.status == 1){
//                                $('.box32').find('span').text(res.num);
//                                $('.section7 ul li:first').find('span').text(res.num);
//                            }
//                        })
//                    }

                    if (data.info) {
                        layer.msg(data.info, {icon: data.icon});
//                        parent.layer.closeAll();//by qiao注释，因为登录时没有提示信息 
                    }
                    if (data.reload) {
                        location.reload();
                    }
                    if (data.parent == 1) {
                        setTimeout(function () {
                            parent.location.reload();
                            parent.layer.closeAll();
                        }, 1);
                    }
                    if (data.url) {
                        setTimeout(function () {
                            location.href = data.url;
                        }, 1000);
                    } else {
                        layer.close(index);
                    }
                }
            })
        } else {
            $('form').submit();
        }

    } else {
        layer.msg("有数据未完善，请填写完整再提交！");
    }
})

$("input[name='password']").keyup(function (e) {
    if (e.keyCode === 13) {
        $('.btn-submit').click();
    }
});

//删除
$(document).on('click', '.delete', function () {
    var url = $(this).attr('data-url');
    var confirm = $(this).attr('data-confirm');
    if (!confirm) {
        confirm = '确定要进行此操作吗？';
    }
    layer.confirm(confirm, {
        closeBtn: 0,
        btn: ['确定', '取消'] //按钮
    }, function () {
        var index = layer.load(2, {shade: false});
        $.ajax({
            url: url,
            type: "get",
            success: function (data) {
                console.log(data);
                if (data.status) {
                    layer.msg('删除成功', {icon: 6});
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                } else {
                    layer.msg('删除失败', {icon: 5});
                    layer.close(index);
                }
            }
        })
    }, function (index) {
        layer.close(index);
    });
});

//全部删除
$('.deleteAll').on('click', function () {
    var url = $(this).attr('data-url');
    var data = $('#ids').serialize();
    layer.confirm('确定要进行此操作吗？', {
        closeBtn: 0,
        btn: ['确定', '取消'] //按钮
    }, function () {
        var index = layer.load(2, {shade: false});
        $.post(url, data, function (res) {
            console.log(res)
            if (res.status) {
                layer.msg('删除成功', {icon: 6});
                setTimeout(function () {
                    location.reload();
                }, 1000);
            } else {
                layer.msg('删除失败', {icon: 5});
                layer.close(index);
            }
        })
    }, function (index) {
        layer.close(index);
    });

})

function dateTime(t) {
    //日期插件
    $('body').on('click', '.datepickerInput', function () {
        _this = $(this);
        var type = $(this).attr('data-type');
        if (type) {
            t = type;
        }
        if (t == 1) {
            $(this).datetimepicker();
        } else if (t == 2) {
            $(this).datetimepicker({
                timeText: '时间',
                hourText: '小时',
                minuteText: '分钟',
                secondText: '秒',
                currentText: '现在',
                closeText: '完成',
                showSecond: true, //显示秒  
                timeFormat: 'HH:mm:ss', //格式化时间  
                onChangeDateTime: function (date, inst) {
                    var datetime = date.getFullYear()
                            + "-"// "年"
                            + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0"
                                    + (date.getMonth() + 1))
                            + "-"// "月"
                            + (date.getDate() < 10 ? "0" + date.getDate() : date
                                    .getDate())
                            + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours())
                            + ":"
                            + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())
                            + ":"
                            + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
                    console.log(datetime);
                    _this.next().val(datetime);


                }
            });
        } else if (t == 3) {
            $(this).datetimepicker({
                lang: 'ch',
                timepicker: false,
                format: 'Y-m-d',
                formatDate: 'Y-m-d',
                onChangeDateTime: function (date, inst) {
                    var datetime = date.getFullYear()
                            + "-"// "年"
                            + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0"
                                    + (date.getMonth() + 1))
                            + "-"// "月"
                            + (date.getDate() < 10 ? "0" + date.getDate() : date
                                    .getDate());
//                    console.log(datetime);
                    var a_weekday = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
                    var date_new = new Date(Date.parse(datetime.replace(/\-/g, "/")));
                    if (_this.next().attr('name') == 'SUBJECT') {
                        $('#subject').val(datetime + " " + a_weekday[date_new.getDay()] + " " + "日志");
                    } else {
                        _this.next().val(datetime);
                    }


                }
            })
        } else {
            $(this).datetimepicker({
                lang: 'ch',
                timepicker: false,
                format: 'Y-m-d',
                formatDate: 'Y-m-d',
            })
        }
    })
}

function initLogin() {
    //更新验证码
    $('.changeCode').on('click', function () {
        var img = $(this).parent().find('img').attr('src') + '?' + Math.random();
        $(this).parent().find('img').attr('src', img)
    })

    //验证验证码
    $('input[name="code"]').on('change', function () {
        var code = $(this).val();
        var url = $(this).attr('data-url');
        $.get(url + '?code=' + code, function (res) {
            console.log(res);
            if (res == 'false') {
                $('.btn-success').removeClass('ajax-post');
                $('.btn-success').removeClass('btn-submit');
                layer.msg('验证码错误');
            } else {
                $('.btn-success').addClass('ajax-post');
                $('.btn-success').addClass('btn-submit');
            }
        })
    })


}


/*
 * 图片及文件上传
 * zhangyingheng <zhang_yh@jsumt.com.cn>
 */
function initUpload(uploadurl,fileType) {
    var upBtn;
    $('body').on('click', '#upload', function () {
        var _this = $(this);
        upBtn = _this;
        $('#inputImage').click();
    });
    $('#inputImage').on("change", function () {
        var imgfile = $("input[name='imgfile']").val();//图片保存文件夹
        var url = $('#fileurl').val();
        var file = $('#filename').val();
        var cont = $('.filename-cont').html();
        $(".cropType").val("one"); //设置裁剪图片的类型
        $.ajaxFileUpload({
            url: uploadurl,
            secureuri: false,
            fileElementId: 'inputImage',
            type: 'POST',
            data: {imgfile: imgfile, fileType: fileType},
            dataType: 'eval',
            success: function (data) {
                var index = data.indexOf(';');   //文件名与路径分开
                if (file) {
                    file += ';' + data.substring(0, index);   //文件名
                } else {
                    file += data.substring(0, index);   //文件名
                }

                if (url) {
                    url += ';' + data.substring(index + 1);    //路径
                } else {
                    url += data.substring(index + 1);    //路径
                }

                var types = data.substring(index + 1).lastIndexOf(".");
                last_type = data.substring(index + 1).substring(types + 1, data.substring(index + 1).length);
                var arr = new Array('png', 'jpg', 'jpeg', 'psd', 'gif');
//                console.log($.inArray(last_type, arr));
                if ($.inArray(last_type, arr) >= 0) {
                    cont += '<span><img src="' + data.substring(index + 1) + '" width="100px"><img src="/Public/Index/img/close.png" style="width:15px" class="pointer delfile" data-fileurl="' + data.substring(index + 1) + '"/>;</span>';
                } else {
                    cont += '<span>' + data.substring(0, index) + '<img src="/Public/Index/img/close.png" style="width:15px" class="pointer delfile" data-fileurl="' + data.substring(index + 1) + '"/>;</span>';
                }

                $('#inputImage').val("");
                if (data !== "false") {
                    if (fileType == 'head') {//by qiao 20180815 修改头像
                        $('#myHead').attr('src', url)
                    } else {
                        //显示文件名
                        $('.filename-cont').html(cont);
                    }
                    //存路径及文件名
                    $('#filename').val(file);
                    $('#fileurl').val(url);
                    dialogOpen();
                }
            }
        });
    });

    //删除上传的文件
    $('body').on('click', '.delfile', function () {
        _this = $(this);
        var url = $('input[name="url"]').val();
        var fileurl = $(this).attr('data-fileurl');
        $.get(url + '?url=' + fileurl, function (res) {
            console.log(res);
            if (res.status) {
                _this.parent('span').remove();
                var name = '';
                $('.up .filename-cont span').each(function () {
                    if ($(this).text()) {
                        name += ';' + $(this).text();
                    }
                })
                $('#filename').val(name);
                var url = '';
                $('.up .filename-cont img').each(function () {
                    if ($(this).attr('data-fileurl')) {
                        url += ';' + $(this).attr('data-fileurl');
                    }

                })
                $('#fileurl').val(url);
                layer.msg('删除成功', {icon: 6});
            } else {
                layer.msg('删除成功', {icon: 5});
            }
        })
    })
}

function initAddCate() {
    //新增类别
    $('.categoryBtn').on('click', function () {
        var ctrl = $(this).attr('data-ctrl');   //控制器名称
        var document_w = $(window).width();
        var document_h = $(window).height();
        var layer_w = '400';
        var layer_h = '500';
        var w = (document_w - layer_w) / 2;
        var h = (document_h - layer_h) / 2;
        layer.open({
            type: 2,
            title: [
                "新增类别",
                'background-color: #437dba;color:#fff;text-align:center;font-size:1.4em',
            ],
            area: [layer_w + 'px', layer_h + 'px'], //宽高
            offset: [h + 'px', w + 'px'], //弹出位置 [top,left]
            content: "/index.php/Home/Index/layer/type/16/ctrl/" + ctrl
        })
    })

    //删除分类
    $('.delCate').on('click', function () {
        var url = $(this).attr('data-url');
        layer.confirm('确定要进行此操作吗？', {
            closeBtn: 0,
            btn: ['确定', '取消'] //按钮
        }, function () {
            var index = layer.load(2, {shade: false});
            $.get(url, function (res) {
                layer.msg(res.info, {icon: res.icon});
                if (res.status == 1) {
                    parent.location.reload();
                }
            })
        }, function (index) {
            layer.close(index);
        });
    })

    //流程类分类弹窗
    $('.addFlowCate').on('click', function () {
        var ctrl = $(this).attr('data-ctrl');   //控制器名称
        var id = $(this).attr('data-id');
        var document_w = $(window).width();
        var document_h = $(window).height();
        var layer_w = '400';
        var layer_h = '500';
        var w = (document_w - layer_w) / 2;
        var h = (document_h - layer_h) / 2;
        layer.open({
            type: 2,
            title: [
                "新增类别",
                'background-color: #437dba;color:#fff;text-align:center;font-size:1.4em',
            ],
            area: [layer_w + 'px', layer_h + 'px'], //宽高
            offset: [h + 'px', w + 'px'], //弹出位置 [top,left]
            content: "/index.php/Home/Index/layer/type/18/ctrl/" + ctrl + "/id/" + id
        })
    })
}
